package com.service.impl;

import com.Exception.NormalException.FileExceptions.FileFormatException;
import com.Result.TwitterWithURLs;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entity.Twitter;
import com.entity.TwitterPicture;
import com.mapper.TwitterPictureMapper;
import com.service.TwitterPictureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XTC
 * @since 2024-07-12
 */
@Service
public class TwitterPictureServiceImpl extends ServiceImpl<TwitterPictureMapper, TwitterPicture> implements TwitterPictureService {
    @Autowired
    private TwitterPictureMapper twitterPictureMapper;

    @Autowired
    private FileService fileService;

    @Override
    public boolean savePictures(Integer twitterId, Integer userId, MultipartFile[] pictures) throws FileFormatException, IOException {
        if(pictures == null || pictures.length == 0) {
            return true;
        }
        if(pictures[0].getOriginalFilename().isEmpty()) {
            return true;
        }
        if(pictures[0].getSize() == 0) {
            return true;
        }
        for(int i = 0; i < pictures.length; i++){
            String fileName = userId + "_" + twitterId + "_" + i;
            String url = fileService.saveFile(pictures[i], "/twitter/picture/", fileName, false);
            TwitterPicture twitterPicture = new TwitterPicture();
            twitterPicture.setTwitterId(twitterId);
            twitterPicture.setFileUrl(url);
            this.twitterPictureMapper.insert(twitterPicture);
        }
        return true;
    }

    @Override
    public List<TwitterWithURLs> setPictureURL(List<Twitter> twitterList) {
        List<TwitterWithURLs> list = new ArrayList<>();
        for(Twitter twitter : twitterList) {
            QueryWrapper<TwitterPicture> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("twitter_id", twitter.getId());
            List<TwitterPicture> pictureList = this.twitterPictureMapper.selectList(queryWrapper);
            List<String> urlList = new ArrayList<>();
            for(TwitterPicture twitterPicture : pictureList){
                urlList.add(twitterPicture.getFileUrl());
            }
            TwitterWithURLs twitterWithURLs = new TwitterWithURLs();
            BeanUtils.copyProperties(twitter, twitterWithURLs);
            twitterWithURLs.setPictureURLList(urlList);
            list.add(twitterWithURLs);
        }
        return list;
    }
}
